import os
import subprocess
from datetime import datetime
import re

def clone_and_clean(url, target_folder, txt_file_path):
    # 检查URL是否符合GitHub仓库的格式
    github_repo_pattern = re.compile(r'https://github.com/([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)$')
    match = github_repo_pattern.match(url)
    
    if not match:
        raise ValueError("输入的URL不是有效的GitHub仓库地址。")
    
    # 构造克隆链接
    user, repo = match.groups()
    clone_url = f"https://github.com/{user}/{repo}.git"
    
    # 创建目标文件夹
    if not os.path.exists(target_folder):
        os.makedirs(target_folder)
    
    # 克隆文件
    try:
        subprocess.run(["git", "clone", clone_url], check=True)
    except subprocess.CalledProcessError as e:
        raise Exception(f"克隆仓库失败: {e}")
    
    # 重命名克隆的文件夹
    current_time = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
    new_folder_name = f"{user}_{repo}_{current_time}"
    os.rename(repo, new_folder_name)
    
    # 移动文件夹到目标文件夹
    new_folder_path = os.path.join(target_folder, new_folder_name)
    os.rename(new_folder_name, new_folder_path)
    
    # 删除.git目录
    git_dir = os.path.join(new_folder_path, '.git')
    if os.path.exists(git_dir):
        subprocess.run(["rm", "-rf", git_dir], check=True)
    
    # 写入信息到.txt文件
    write_repo_info_to_file(url, txt_file_path, new_folder_path)
    
    # 返回克隆并清理后的文件夹的绝对路径
    return os.path.abspath(new_folder_path)

def write_repo_info_to_file(url, file_path, folder_path):
    # 检查文件是否已存在
    if os.path.exists(file_path):
        with open(file_path, 'r') as file:
            content = file.read()
            # 检查内容是否已包含当前URL
            if url in content:
                return  # 如果已包含，则不写入

    # 获取用户和仓库名称
    github_repo_pattern = re.compile(r'https://github.com/([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)$')
    match = github_repo_pattern.match(url)
    user, repo = match.groups()

    # 构造要写入的信息
    repo_info = f"URL: {url}\nUser: {user}\nRepository: {repo}\nCloned Folder: {folder_path}\n\n"

    # 写入信息到文件
    with open(file_path, 'a') as file:
        file.write(repo_info)

# 示例使用
if __name__ == "__main__":
    try:
        url = input("请输入GitHub仓库URL: ")
        target_folder = "cloned_repos"  # 存放克隆的仓库的文件夹
        txt_file_path = "repos_info.txt"  # 存储仓库信息的.txt文件
        abs_path = clone_and_clean(url, target_folder, txt_file_path)
        print(f"仓库已克隆并清理.git目录, 存放在: {abs_path}")
    except Exception as e:
        print(f"出现错误: {e}")
